package com.kuang.pool;

import java.util.concurrent.*;

/**
 * @author luomingliang
 * @date 2021/5/24 22:19
 */
public class Demo01 {
    //Executors 工具类， 3大方法
    //使用了线程池之后，使用线程池来创建线程
    public static void main(String[] args) {
        //单个线程
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //创建一个固定大小的线程池
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //可伸缩的，遇强则强，遇弱则弱
//         ExecutorService threadPool = Executors.newCachedThreadPool();

        /**
         * AbortPolicy 队列满了，还有线程进来，不处理这个线程，抛出异常
         * CallerRunsPolicy 队列满了，哪里来的哪里去
         * DiscardPolicy 队列满了，不会抛出异常，直接丢弃任务
         * DiscardOldestPolicy 队列满了，尝试和最早的竞争，也不会抛出异常
         */
        //打印出电脑的CPU核数
        System.out.println(Runtime.getRuntime().availableProcessors());
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" OK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完，程序结束，关闭线程池
            threadPool.shutdown();
        }
    }
}
